package sk.tuke.lara.masplc.agents;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import sk.tuke.lara.masplc.Conversations;
import sk.tuke.lara.masplc.utils.CommunicationUtils;
import sk.tuke.lara.masplc.utils.MsgTemplateFactory;

public class RequirementsRequestBehaviour extends CyclicBehaviour {

    private static final long serialVersionUID = -9138156882412765201L;
    private MessageTemplate requirementsMT;
    private PlcAgent myAgent;

    public RequirementsRequestBehaviour(PlcAgent myAg) {
        this.myAgent = myAg;
        requirementsMT = MsgTemplateFactory.matchConversiation(Conversations.REQUIREMENTS, myAgent.getAID());
    }

    @Override
    public void action() {
        ACLMessage msg = myAgent.receive(requirementsMT);
        if (msg != null) {
            System.out.println(" sending local Requirements to " + msg.getSender().getName());
            PlcAgentDTO localInformations = new PlcAgentDTO();
            localInformations.setName(myAgent.getLocalName());
            localInformations.setMaxVykon(myAgent.maxVykon);
            localInformations.setPriority(myAgent.priority);
            for (ConstraintsDTO c : myAgent.constraintsList) {
                localInformations.getConstraints().add(c);
            }

            ACLMessage response = new ACLMessage(ACLMessage.AGREE);
            response.setContent(CommunicationUtils.toJson(localInformations));
            response.setConversationId(msg.getConversationId());
            response.addReceiver(msg.getSender());
            myAgent.send(response);

        } else {
            // wait for others
            block();
        }
    }
}
